home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / cpp_libs / cool / ge_cool.lha / GE_COOL2.1 / cpp / cpp1.c < prev    next >
Text File  |  1992-04-13  |  28KB  |  831 lines

  1. /*
  2.  
  3.  
  4.  Copyright (C) 1990 Texas Instruments Incorporated.
  5.  
  6.  Permission is granted to any individual or institution to use, copy, modify,
  7.  and distribute this software, provided that this complete copyright and
  8.  permission notice is maintained, intact, in all copies and supporting
  9.  documentation.
  10.  
  11.  Texas Instruments Incorporated provides this software "as is" without
  12.  express or implied warranty.
  13.  
  14.  
  15.  * CPP main program.
  16.  *
  17.  * Edit history
  18.  * 21-May-84    MM    "Field test" release
  19.  * 23-May-84    MM    Some minor hacks.
  20.  * 30-May-84    ARF    Didn't get enough memory for __DATE__
  21.  *            Added code to read stdin if no input
  22.  *            files are provided.
  23.  * 29-Jun-84    MM    Added ARF's suggestions, Unixifying cpp.
  24.  * 11-Jul-84    MM    "Official" first release (that's what I thought!)
  25.  * 22-Jul-84    MM/ARF/SCK Fixed line number bugs, added cpp recognition
  26.  *            of #line, fixed problems with #include.
  27.  * 23-Jul-84    MM    More (minor) include hacking, some documentation.
  28.  *            Also, redid cpp's #include files
  29.  * 25-Jul-84    MM    #line filename isn't used for #include searchlist
  30.  *            #line format is <number> <optional name>
  31.  * 25-Jul-84    ARF/MM    Various bugs, mostly serious.  Removed homemade doprint
  32.  * 01-Aug-84    MM    Fixed recursion bug, remove extra newlines and
  33.  *            leading whitespace from cpp output.
  34.  * 02-Aug-84    MM    Hacked (i.e. optimized) out blank lines and unneeded
  35.  *            whitespace in general.  Cleaned up unget()'s.
  36.  * 03-Aug-84    Keie    Several bug fixes from Ed Keizer, Vrije Universitet.
  37.  *            -- corrected arg. count in -D and pre-defined
  38.  *            macros.  Also, allow \n inside macro actual parameter
  39.  *            lists.
  40.  * 06-Aug-84    MM    If debugging, dump the preset vector at startup.
  41.  * 12-Aug-84    MM/SCK    Some small changes from Sam Kendall
  42.  * 15-Aug-84    Keie/MM    cerror, cwarn, etc. take a single string arg.
  43.  *            cierror, etc. take a single int. arg.
  44.  *            changed LINE_PREFIX slightly so it can be
  45.  *            changed in the makefile.
  46.  * 31-Aug-84    MM    USENET net.sources release.
  47.  *  7-Sep-84    SCH/ado Lint complaints
  48.  * 10-Sep-84    Keie    Char's can't be signed in some implementations
  49.  * 11-Sep-84    ado    Added -C flag, pathological line number fix
  50.  * 13-Sep-84    ado    Added -E flag (does nothing) and "-" file for stdin.
  51.  * 14-Sep-84    MM    Allow # 123 as a synonym for #line 123
  52.  * 19-Sep-84    MM    scanid always reads to token, make sure #line is
  53.  *            written to a new line, even if -C switch given.
  54.  *            Also, cpp - - reads stdin, writes stdout.
  55.  * 03-Oct-84    ado/MM    Several changes to line counting and keepcomments
  56.  *            stuff.  Also a rewritten control() hasher -- much
  57.  *            simpler and no less "perfect". Note also changes
  58.  *            in cpp3.c to fix numeric scanning.
  59.  * 04-Oct-84    MM    Added recognition of macro formal parameters if
  60.  *            they are the only thing in a string, per the
  61.  *            draft standard.
  62.  * 08-Oct-84    MM    One more attack on scannumber
  63.  * 15-Oct-84    MM/ado    Added -N to disable predefined symbols.  Fixed
  64.  *            linecount if COMMENT_INVISIBLE enabled.
  65.  * 22-Oct-84    MM    Don't evaluate the #if/#ifdef argument if
  66.  *            compilation is supressed.  This prevents
  67.  *            unnecessary error messages in sequences such as
  68.  *                #ifdef FOO        -- undefined
  69.  *                #if FOO == 10    -- shouldn't print warning
  70.  * 25-Oct-84    MM    Fixed bug in false ifdef supression.  On vms,
  71.  *            #include <foo> should open foo.h -- this duplicates
  72.  *            the behavior of Vax-C
  73.  * 31-Oct-84    ado/MM    Parametized $ in indentifiers.  Added a better
  74.  *            token concatenator and took out the trial
  75.  *            concatenation code.  Also improved #ifdef code
  76.  *            and cleaned up the macro recursion tester.
  77.  *  2-Nov-84    MM/ado    Some bug fixes in token concatenation, also
  78.  *            a variety of minor (uninteresting) hacks.
  79.  *  6-Nov-84    MM    Happy Birthday.  Broke into 4 files and added
  80.  *            #if sizeof (basic_types)
  81.  *  9-Nov-84    MM    Added -S* for pointer type sizes
  82.  * 13-Nov-84    MM    Split cpp1.c, added vms defaulting
  83.  * 23-Nov-84    MM/ado    -E supresses error exit, added CPP_INCLUDE,
  84.  *            fixed strncpy bug.
  85.  *  3-Dec-84    ado/MM    Added OLD_PREPROCESSOR
  86.  *  7-Dec-84    MM    Stuff in Nov 12 Draft Standard
  87.  * 17-Dec-84    george    Fixed problems with recursive macros
  88.  * 17-Dec-84    MM    Yet another attack on #if's (f/t)level removed.
  89.  * 07-Jan-85    ado    Init defines before doing command line options
  90.  *            so -Uunix works.
  91.  * 21-Oct-85    RMS    Rename `token' to `tokenbuf'.
  92.  *            Allocate it dynamically, with size in `tokenbsize'.
  93.  * 23-Oct-85    RMS    Do not print message about number of errors.
  94.  *
  95.  * 19-Jan-90    DKM     Support for MVS.
  96.  * 04-May-90    MJF     Added predefined constant for target_arch.
  97.  * 18-May-90    MBN     Conditional compilation on COOL to get "clean" cpp
  98.  * 21-May-90    MJF     Added DECLARE_ONCE for CCC -X
  99.  * 20-Aug-90    MJF     Added typecase external function reference
  100.  * 16-Jun-91    GPD     Added support for Sun -Y option
  101.  *             Fix -N by putting initdefines() after dooptions()
  102.  *             Added throw macro support to jump table
  103.  * 25-Jun-91    GPD    Fixes to make ## operator expansion ANSI conformant.
  104.  * 07-Jul-91    GPD    Fix #line nesting. Added wrongfile.
  105.  */
  106.  
  107. /*)BUILD
  108.     $(PROGRAM)    = cpp
  109.     $(FILES)    = { cpp1 cpp2 cpp3 cpp4 cpp5 cpp6 }
  110.     $(INCLUDE)    = { cppdef.h cpp.h }
  111.     $(STACK)    = 2000
  112.     $(TKBOPTIONS)    = {
  113.         STACK    = 2000
  114.     }
  115. */
  116.  
  117. /*    DOCUMENTATION
  118.  
  119. title    cpp        C Pre-Processor
  120. index            C pre-processor
  121.  
  122. synopsis
  123.     cpp [-options] [infile [outfile]]
  124.  
  125. description
  126.  
  127.     CPP reads a C source file, expands macros and include
  128.     files, and writes an input file for the C compiler.
  129.     If no file arguments are given, CPP reads from stdin
  130.     and writes to stdout.  If one file argument is given,
  131.     it will define the input file, while two file arguments
  132.     define both input and output files.  The file name "-"
  133.     is a synonym for stdin or stdout as appropriate.
  134.  
  135.     The following options are supported.  Options may
  136.     be given in either case.
  137.  
  138.     -C        If set, source-file comments are written
  139.     to the output file.  This allows the output of CPP to be
  140.     used as the input to a program, such as lint, that expects
  141.     commands embedded in specially-formatted comments.
  142.  
  143.     -Dname=value    Define the name as if the programmer wrote
  144.  
  145.         #define name value
  146.  
  147.     at the start of the first file.  If "=value" is not
  148.     given, a value of "1" will be used.
  149.  
  150.     On non-unix systems, all alphabetic text will be forced
  151.     to upper-case.
  152.  
  153.     -E        Always return "success" to the operating
  154.     system, even if errors were detected.  Note that some fatal
  155.     errors, such as a missing #include file, will terminate
  156.     CPP, returning "failure" even if the -E option is given.
  157.  
  158.     -Idirectory    Add this directory to the list of
  159.     directories searched for #include "..." and #include <...>
  160.     commands.  Note that there is no space between the
  161.     "-I" and the directory string.  More than one -I command
  162.     is permitted.  On non-Unix systems "directory" is forced
  163.     to upper-case.
  164.  
  165.     -N        CPP normally predefines some symbols defining
  166.     the target computer and operating system.  If -N is specified,
  167.     no symbols will be predefined.  If -N -N is specified, the
  168.     "always present" symbols, __LINE__, __FILE__, and __DATE__
  169.     are not defined.
  170.  
  171.     -Stext        CPP normally assumes that the size of
  172.     the target computer's basic variable types is the same as the size
  173.     of these types of the host computer.  (This can be overridden
  174.     when CPP is compiled, however.)  The -S option allows dynamic
  175.     respecification of these values.  "text" is a string of
  176.     numbers, separated by commas, that specifies correct sizes.
  177.     The sizes must be specified in the exact order:
  178.  
  179.         char short int long float double
  180.  
  181.     If you specify the option as "-S*text", pointers to these
  182.     types will be specified.  -S* takes one additional argument
  183.     for pointer to function (e.g. int (*)())
  184.  
  185.     For example, to specify sizes appropriate for a PDP-11,
  186.     you would write:
  187.  
  188.            c s i l f d func
  189.          -S1,2,2,2,4,8,
  190.         -S*2,2,2,2,2,2,2
  191.  
  192.     Note that all values must be specified.
  193.  
  194.     -Uname        Undefine the name as if
  195.  
  196.         #undef name
  197.  
  198.     were given.  On non-Unix systems, "name" will be forced to
  199.     upper-case.
  200.  
  201.     -Xnumber    Enable debugging code.  If no value is
  202.                     given, a value of 1 will be used.
  203.         -X1             debug print of files #included
  204.         -X2             debug inserts #control as comments in output
  205.         -X3             debug does both -X1 and -X2
  206.  
  207. Pre-Defined Variables
  208.  
  209.     When CPP begins processing, the following variables will
  210.     have been defined (unless the -N option is specified):
  211.  
  212.     Target computer (as appropriate):
  213.  
  214.         pdp11, vax, M68000 m68000 m68k
  215.  
  216.     Target operating system (as appropriate):
  217.  
  218.         rsx, rt11, vms, unix
  219.  
  220.     Target compiler (as appropriate):
  221.  
  222.         decus, vax11c
  223.  
  224.     The implementor may add definitions to this list.
  225.     The default definitions match the definition of the
  226.     host computer, operating system, and C compiler.
  227.  
  228.     The following are always available unless undefined (or
  229.     -N was specified twice):
  230.  
  231.     __FILE__    The input (or #include) file being compiled
  232.     (as a quoted string).
  233.  
  234.     __LINE__    The line number being compiled.
  235.  
  236.     __DATE__    The date of compilation as "Mmm dd yy"
  237.  
  238.     __TIME__    The time of compilation as "hh:mm:ss"
  239.  
  240.     __STDC__    The constant 1.
  241.  
  242.     Thus,
  243.         printf("Bug at line %s,", __LINE__);
  244.         printf(" source file %s", __FILE__);
  245.         printf(" compiled on %s", __DATE__);
  246.  
  247. Draft Proposed Ansi Standard Considerations
  248.  
  249.     When CPP is itself compiled, many features of the Draft
  250.     Proposed Standard that are incompatible with existing
  251.     preprocessors may be disabled.  See the comments in CPP's
  252.     source for details.
  253.  
  254.     Comments are removed from the input text.  The comment
  255.     is replaced by a single space character.  The -C option
  256.     preserves comments, writing them to the output file.
  257.  
  258.     The '$' character is considered to be a letter.  This is
  259.     a permitted extension.
  260.  
  261.     The following new features of C are processed by CPP:
  262.     #elif expression    (_#else _#if)
  263.     '\xNNN'             (Hexadecimal constant)
  264.     '\a'                (Ascii BELL)
  265.     '\v'                (Ascii Vertical Tab)
  266.     #if defined NAME    1 if defined, 0 if not
  267.     #if defined (NAME)  1 if defined, 0 if not  
  268.     #if sizeof (basic type)
  269.     unary +
  270.     U, 123LU            Unsigned ints and longs.
  271.     12.3L               Long double numbers
  272.     token_#token        Token concatenation
  273.     #include token      Expands to filename
  274.         #error tokens       Flags an error
  275.  
  276.     The Draft Proposed Standard has extended C, adding a constant
  277.     string concatenation operator, where
  278.  
  279.         "foo" "bar"
  280.  
  281.     is regarded as the single string "foobar".  (This does not
  282.     affect CPP's processing but does permit a limited form of
  283.     macro argument substitution into strings as will be discussed.)
  284.  
  285.     The Standard Committee plans to add token concatenation
  286.     to #define command lines as follows:
  287.     The sequence "Token1 ## Token2" is treated
  288.     as if the programmer wrote "Token1Token2".  This could
  289.     be used as follows:
  290.  
  291.         #line 123
  292.         #define ATLINE foo ## __LINE__
  293.  
  294.     ATLINE would be defined as foo123.
  295.  
  296.     If the tokens T1 and T2 are concatenated into T3,
  297.     this implementation operates as follows:
  298.  
  299.       1. Expand T1 if it is a macro.
  300.       2. Expand T2 if it is a macro.
  301.       3. Join the tokens, forming T3.
  302.       4. Expand T3 if it is a macro.
  303.  
  304.         If a macro parameter is immediately proceeded by a #, string
  305.         quotes (") are placed around the substituted parameter and
  306.         a \ character is inserted before each " or \ character that
  307.         appears surrounding,or inside a string literal or character
  308.         constant in the argument.
  309.  
  310.         Example:
  311.         #define vprint(name, size) \
  312.           printf(#name "[" "size" "] = {\n")
  313.           ... vprint(vector, 123);
  314.  
  315.     expands (effectively) to
  316.  
  317.           vprint("vector[123] = {\n");
  318.  
  319.     Note that this will be useful if your C compiler supports
  320.     the new string concatenation operation noted above.
  321.  
  322. EXTENSIONS
  323.  
  324.     An extended macro facility is provided which allows and arbitrary unix
  325.     process to act as a macro expander.  To define a macro do one of the
  326.     following:
  327.  
  328.     #pragma defmacro name <file> options
  329.     #pragma defmacro name "file" options
  330.     #pragma defmacro name program options
  331.  
  332.     This provides a mapping between macro names and the file to be
  333.     executed, which is on the include search path. "options" is zero or
  334.         more of the following: 
  335.     recursive    - when present, the macro may be recursively expanded.
  336.     expanding    - when present, input to the macro is macro-expanded.
  337.     delimiter=?  - the default delimiter of ; is replaced with ?
  338.     condition=?  - expand only if this char found after name
  339.     other        - unknown options are passed as arguments to the
  340.                macro expander.
  341.  
  342.     When a "defmacro" style macro's name is found, the name and everything
  343.     until the delimiter (includling all matching {} [] () <> "" '' and
  344.     comments found along the way) is piped into the macro procedure's
  345.     standard-input.  The procedure's standard output is scanned by CPP for
  346.     further processing. The expansion replaces the macro call.
  347.     number.
  348.  
  349. error messages
  350.  
  351.     Many.  CPP prints warning or error messages if you try to
  352.     use multiple-byte character constants (non-transportable)
  353.     if you #undef a symbol that was not defined, or if your
  354.     program has potentially nested comments.
  355.  
  356. authors
  357.  
  358.     Martin Minow (Origional version)
  359.         LaMott Oren  (Macro extensions and ANSI compatability)
  360.  
  361. bugs
  362.  
  363.     The #if expression processor uses signed integers only.
  364.     I.e, #if 0xFFFFu < 0 may be TRUE.
  365.  
  366.         This program differs from tha ANSI specification as follows:
  367.       Trigraph sequences aren't implemented.
  368.  
  369. */
  370.  
  371. #include    <stdio.h>
  372. #include    <ctype.h>
  373. #include    "cppdef.h"
  374. #include    "cpp.h"
  375.  
  376. #if HOST == SYS_MVS
  377. extern char *_stdiamp = "prompt=";  /* no prompting from sysin */
  378. extern char *_stdoamp = "print=no"; /* stdout doesn't need page fmt attr. */
  379. extern char *_stdeamp = "print=no"; /* stderr doesn't need page fmt attr. */
  380. #endif
  381.  
  382. #ifdef COOL
  383. /*
  384.  * Table of internal macros
  385.  *   (Alternating strings and function pointers, termnated with NULL)
  386.  */
  387. extern int parmtype();            /* Make names for parameterized types */
  388. extern int define_symbol();         /* Define a symbol in a package */
  389. extern int define_macro();        /* Define a fancy macro */
  390. extern int member();            /* Symbolic equality test */
  391. extern int class_macro();        /* C++ class processing */
  392. extern int classmac();            /* C++ class processing */
  393. extern int template();            /* Paramertized type definition */
  394. extern int declare();            /* Paramertized type declaration */
  395. extern int declare_once();        /* Paramertized type declaration */
  396. extern int implement();            /* Paramertized type code generation */
  397. extern int implement_n();        /* Paramertized type code generation */
  398. extern int exception();            /* Error recovery code generation */
  399. extern int generate();            /* macro looping mechanism */
  400. extern int compress();            /* compress out white space */
  401. extern int typecase();            /* typecase macro */
  402. extern int throw();            /* throw macro */
  403.  
  404. struct expander_pair internal_macros[] = {
  405.   {"parmtype", parmtype},
  406.   {"define_symbol", define_symbol},
  407.   {"macro", define_macro},
  408.   {"member", member},
  409.   {"class", class_macro},
  410.   {"classmac", classmac},
  411.   {"template", template},
  412.   {"declare", declare},
  413.   {"declare_once", declare_once},
  414.   {"implement", implement},
  415.   {"implement_n", implement_n},
  416.   {"exception", exception},
  417.   {"generate", generate},
  418.   {"compress", compress},
  419.   {"typecase", typecase},
  420.   {"throw", throw},
  421.   {NULL, NULL}};
  422.  
  423. #endif
  424.  
  425. /*
  426.  * Commonly used global variables:
  427.  * line        is the current input line number.
  428.  * wrongline    is set in many places when the actual output
  429.  *        line is out of sync with the numbering, e.g,
  430.  *        when expanding a macro with an embedded newline.
  431.  * wrongfile    is set when the reason for the output line being
  432.  *        out of sync is because we have just left a nested
  433.  *        include file.
  434.  *
  435.  * tokenbuf    holds the last identifier scanned (which might
  436.  *        be a candidate for macro expansion).
  437.  * errors    is the running cpp error counter.
  438.  * infile    is the head of a linked list of input files (extended by
  439.  *        #include and macros being expanded).  infile always points
  440.  *        to the current file/macro.  infile->parent to the includer,
  441.  *        etc.  infile->fd is NULL if this input stream is a macro.
  442.  */
  443. int        line;            /* Current line number        */
  444. int        wrongline;        /* Force #line to compiler    */
  445. int        wrongfile = FALSE;    /* Force #line to compiler    */
  446. char        *tokenbuf;        /* Buffer for current input token */
  447. int        tokenbsize;        /* Allocated size of tokenbuf, */
  448.                     /* not counting zero at end.  */
  449. int        errors;            /* cpp error counter        */
  450. FILEINFO    *infile = NULL;        /* Current input file        */
  451. int        debug;            /* TRUE if debugging now    */
  452. char        *altincl = NULL;    /* Alternate std include dir    */
  453.                     /* Set using -Y option        */
  454. /*
  455.  * This counter is incremented when a macro expansion is initiated.
  456.  * If it exceeds a built-in value, the expansion stops -- this tests
  457.  * for a runaway condition:
  458.  *    #define X Y
  459.  *    #define Y X
  460.  *    X
  461.  * This can be disabled by falsifying rec_recover.  (Nothing does this
  462.  * currently: it is a hook for an eventual invocation flag.)
  463.  */
  464. int        recursion;        /* Infinite recursion counter    */
  465. int        rec_recover = TRUE;    /* Unwind recursive macros    */
  466. DEFBUF            *macro;                /* Catches start of infinite macro */
  467.  
  468. /*
  469.  * instring is set TRUE when a string is scanned.  It modifies the
  470.  * behavior of the "get next character" routine, causing all characters
  471.  * to be passed to the caller (except <DEF_MAGIC>).  Note especially that
  472.  * comments and \<newline> are not removed from the source.  (This
  473.  * prevents cpp output lines from being arbitrarily long).
  474.  *
  475.  * inmacro is set by #define -- it absorbs comments and converts
  476.  * form-feed and vertical-tab to space, but returns \<newline>
  477.  * to the caller.  Strictly speaking, this is a bug as \<newline>
  478.  * shouldn't delimit tokens, but we'll worry about that some other
  479.  * time -- it is more important to prevent infinitly long output lines.
  480.  *
  481.  * instring and inmarcor are parameters to the get() routine which
  482.  * were made global for speed.
  483.  */
  484. int        instring = FALSE;    /* TRUE if scanning string    */
  485. int        inmacro = FALSE;    /* TRUE if #defining a macro    */
  486.  
  487. /*
  488.  * work[] and workp are used to store one piece of text in a temporay
  489.  * buffer.  To initialize storage, set workp = work.  To store one
  490.  * character, call save(c);  (This will fatally exit if there isn't
  491.  * room.)  To terminate the string, call save(EOS).  Note that
  492.  * the work buffer is used by several subroutines -- be sure your
  493.  * data won't be overwritten.  The extra byte in the allocation is
  494.  * needed for string formal replacement.
  495.  */
  496. char        work[NWORK + 1];    /* Work buffer            */
  497. char        *workp;            /* Work buffer pointer        */
  498.  
  499. /*
  500.  * keepcomments is set TRUE by the -C option.  If TRUE, comments
  501.  * are written directly to the output stream.  This is needed if
  502.  * the output from cpp is to be passed to lint (which uses commands
  503.  * embedded in comments).  cflag contains the permanent state of the
  504.  * -C flag.  keepcomments is always falsified when processing #control
  505.  * commands and when compilation is supressed by a false #if
  506.  *
  507.  * If eflag is set, CPP returns "success" even if non-fatal errors
  508.  * were detected.
  509.  *
  510.  * If nflag is non-zero, no symbols are predefined except __LINE__.
  511.  * __FILE__, and __DATE__.  If nflag > 1, absolutely no symbols
  512.  * are predefined.
  513.  */
  514. int        keepcomments = FALSE;    /* Write out comments flag    */
  515. int        cflag = FALSE;        /* -C option (keep comments)    */
  516. int        eflag = FALSE;        /* -E option (never fail)    */
  517. int        nflag = 0;        /* -N option (no predefines)    */
  518. int        yflag = FALSE;        /* -Y option (replace std incl)    */
  519.  
  520. /*
  521.  * ifstack[] holds information about nested #if's.  It is always
  522.  * accessed via *ifptr.  The information is as follows:
  523.  *    WAS_COMPILING    state of compiling flag at outer level.
  524.  *    ELSE_SEEN    set TRUE when #else seen to prevent 2nd #else.
  525.  *    TRUE_SEEN    set TRUE when #if or #elif succeeds
  526.  * ifstack[0] holds the compiling flag.  It is TRUE if compilation
  527.  * is currently enabled.  Note that this must be initialized TRUE.
  528.  */
  529. char        ifstack[BLK_NEST] = { TRUE };    /* #if information    */
  530. char        *ifptr = ifstack;        /* -> current ifstack[] */
  531.  
  532. /*
  533.  * incdir[] stores the -i directories (and the system-specific
  534.  * #include <...> directories.
  535.  */
  536. char    *incdir[NINCLUDE];        /* -i directories        */
  537. char    **incend = incdir;        /* -> free space in incdir[]    */
  538.  
  539. /*
  540.  * This is the table used to predefine target machine and operating
  541.  * system designators.  It may need hacking for specific circumstances.
  542.  * Note: it is not clear that this is part of the Ansi Standard.
  543.  * The -N option supresses preset definitions.
  544.  */
  545. char    *preset[] = {            /* names defined at cpp start    */
  546. #ifdef    MACHINE
  547.     MACHINE,
  548. #endif
  549. #ifdef    SYSTEM
  550.     SYSTEM,
  551. #endif
  552. #ifdef    TARGET_ARCH
  553.     TARGET_ARCH,
  554. #endif
  555. #ifdef    COMPILER
  556.     COMPILER,
  557. #endif
  558. #ifdef  CH_SET
  559.          CH_SET,
  560. #endif
  561. #if    DEBUG
  562.     "decus_cpp",            /* Ourselves!            */
  563. #endif
  564.     NULL                /* Must be last            */
  565. };
  566.  
  567.  
  568. main(argc, argv)
  569. int        argc;
  570. char        *argv[];
  571. {
  572.     register int    i;
  573.  
  574. #if HOST == SYS_VMS
  575.     argc = getredirection(argc, argv);    /* vms >file and <file    */
  576. #endif
  577.     i = dooptions(argc, argv);        /* Command line -flags    */
  578.     initdefines();                /* O.S. specific def's    */
  579.     switch (i) {
  580.     case 3:
  581.         /*
  582.          * Get output file, "-" means use stdout.
  583.          */
  584.         if (!streq(argv[2], "-")) {
  585. #if HOST == SYS_VMS
  586.         /*
  587.          * On vms, reopen stdout with "vanilla rms" attributes.
  588.          */
  589.         if ((i = creat(argv[2], 0, "rat=cr", "rfm=var")) == -1
  590.          || dup2(i, fileno(stdout)) == -1) {
  591. #else
  592.         if (freopen(argv[2], "w", stdout) == NULL) {
  593. #endif
  594.             perror(argv[2]);
  595.             cerror("Can't open output file \"%s\"", argv[2]);
  596.             exit(IO_ERROR);
  597.         }
  598.         }                /* Continue by opening input    */
  599.     case 2:                /* One file -> stdin        */
  600.         /*
  601.          * Open input file, "-" means use stdin.
  602.          */
  603.         if (!streq(argv[1], "-")) {
  604.         if (freopen(argv[1], "r", stdin) == NULL) {
  605.             perror(argv[1]);
  606.             cerror("Can't open input file \"%s\"", argv[1]);
  607.             exit(IO_ERROR);
  608.         }
  609.         strcpy(work, argv[1]);    /* Remember input filename    */
  610.         break;
  611.         }                /* Else, just get stdin        */
  612.     case 0:                /* No args?            */
  613.     case 1:                /* No files, stdin -> stdout    */
  614. #if (HOST == SYS_UNIX  || HOST == SYS_OS2 || HOST == SYS_XENIX || HOST == SYS_MVS || HOST == SYS_AIX)
  615.         work[0] = EOS;        /* Unix can't find stdin name    */
  616. #else
  617.         fgetname(stdin, work);    /* Vax-11C, Decus C know name    */
  618. #endif
  619.         break;
  620.  
  621.     default:
  622.         exit(IO_ERROR);        /* Can't happen            */
  623.     }
  624.     setincdirs();            /* Setup -I include directories    */
  625.     addfile(stdin, work);        /* "open" main input file    */
  626. #if DEBUG
  627.     if (debug > 0)
  628.         dumpdef("preset #define symbols");
  629. #endif
  630.     cppmain();            /* Process main file        */
  631.     if ((i = (ifptr - &ifstack[0])) != 0) {
  632. #if OLD_PREPROCESSOR
  633.         ciwarn("Inside #ifdef block at end of input, depth = %d", i);
  634. #else
  635.         cierror("Inside #ifdef block at end of input, depth = %d", i);
  636. #endif
  637.     }
  638.     fclose(stdout);
  639.     if (errors > 0 && !eflag)
  640.       exit(IO_ERROR);
  641. #ifdef COOL
  642.     finish_symbols();
  643. #endif
  644.     exit(IO_NORMAL);        /* No errors or -E option set    */
  645. }
  646.  
  647. FILE_LOCAL
  648. cppmain()
  649. /*
  650.  * Main process for cpp -- copies tokens from the current input
  651.  * stream (main file, include file, or a macro) to the output
  652.  * file.
  653.  */
  654. {
  655.     register int        c;        /* Current character    */
  656.     register int        counter;    /* newlines and spaces    */
  657.     extern int        output();    /* Output one character    */
  658.  
  659.     /* Initialize for reading tokens */
  660.     tokenbsize = 50;
  661.     tokenbuf = getmem (tokenbsize + 1);
  662.  
  663.     /*
  664.      * Explicitly output a #line at the start of cpp output so
  665.      * that lint (etc.) knows the name of the original source
  666.      * file.  If we don't do this explicitly, we may get
  667.      * the name of the first #include file instead.
  668.      */
  669.     sharp();
  670.     /*
  671.      * This loop is started "from the top" at the beginning of each line
  672.      * wrongline is set TRUE in many places if it is necessary to write
  673.      * a #line record.  (But we don't write them when expanding macros.)
  674.      *
  675.      * The counter variable has two different uses:  at
  676.      * the start of a line, it counts the number of blank lines that
  677.      * have been skipped over.  These are then either output via
  678.      * #line records or by outputting explicit blank lines.
  679.       * When expanding tokens within a line, the counter remembers
  680.      * whether a blank/tab has been output.  These are dropped
  681.      * at the end of the line, and replaced by a single blank
  682.      * within lines.
  683.      */
  684.     for (;;) {
  685.         counter = 0;            /* Count empty lines    */
  686.         for (;;) {                /* For each line, ...    */
  687.           while (type[(c = get())] == SPA) /* Skip leading blanks    */
  688.         if (keepcomments)        /* in this line.    */
  689.           putchar(c);
  690.           if (c == '\n')            /* If line's all blank,    */
  691.         if (wrongfile)
  692.           counter = 0;
  693.         else if (keepcomments)
  694.           putchar('\n');
  695.         else
  696.           ++counter;            /* Do nothing now    */
  697.           else if (c == '#') {        /* Is 1st non-space '#'    */
  698.         keepcomments = FALSE;        /* Don't pass comments    */
  699.         counter = control(counter);    /* Yes, do a #command    */
  700.         keepcomments = (cflag && compiling);
  701.           }
  702.           else if (c == EOF_CHAR)        /* At end of file?    */
  703.         break;
  704.           else if (!compiling) {        /* #ifdef false?    */
  705.         skipnl();            /* Skip to newline    */
  706.         if(keepcomments)
  707.           putchar('\n');
  708.         else
  709.           counter++;            /* Count it, too.    */
  710.           }
  711.           else {
  712.         break;                /* Actual token        */
  713.           }
  714.         }
  715.         if (c == EOF_CHAR)            /* Exit process at    */
  716.         break;                /* End of file        */
  717.         /*
  718.          * If the loop didn't terminate because of end of file, we
  719.          * know there is a token to compile.  First, clean up after
  720.          * absorbing newlines.  counter has the number we skipped.
  721.          */
  722.         if (wrongline && infile->fp != NULL)
  723.         sharp();            /* Output # line number    */
  724.         else {                /* If just a few, stuff    */
  725.         while (--counter >= 0)        /* them out ourselves    */
  726.             putchar('\n');
  727.         }
  728.         /*
  729.          * Process each token on this line.
  730.          */
  731.         unget();                /* Reread the char.    */
  732.         for (;;) {                /* For the whole line,    */
  733.           for (counter = 0; (type[(c = get())] == SPA);) {
  734.         if(keepcomments)
  735.           putchar(c);
  736.         else {
  737. #if COMMENT_INVISIBLE
  738.           if (c != COM_SEP)
  739.             counter++;
  740. #else
  741.           counter++;          /* Skip over blanks    */
  742. #endif
  743.         }
  744.           }
  745.           if (c == EOF_CHAR || c == '\n')
  746.         goto end_line;          /* Exit line loop    */
  747.           else if (counter > 0)      /* If we got any spaces    */
  748.         putchar(' ');          /* Output one space    */
  749.           c = macroid(c);          /* Grab the token    */
  750.           if (c == EOF_CHAR || c == '\n') /* From macro exp error    */
  751.         goto end_line;          /* Exit line loop    */
  752.           switch (type[c]) {
  753.           case LET:
  754.         fputs(tokenbuf, stdout);  /* Quite ordinary token    */
  755.         break;
  756.  
  757.  
  758.           case DOT:              /* Dot may begin floats    */
  759.         if (type[get()] != DIG)
  760.         {
  761.             unget();
  762.             output('.');
  763.             break;          /* Not a float after all    */
  764.         }
  765.         else
  766.             unget();          /* Fall through    */
  767.  
  768.           case DIG:              /* Output a number    */
  769.         scannumber(c, output);
  770.         c = get();
  771.         if (type[c] == LET || c == '.')
  772.         {
  773.             scanid(c);        /* Don't expand id after num    */
  774.             fputs(tokenbuf, stdout);
  775.         }
  776.         else
  777.             unget();
  778.         break;
  779.  
  780.           case QUO:              /* char or string const    */
  781.         scanstring(c, output);      /* Copy it to output    */
  782.         break;
  783.  
  784.           default:              /* Some other character    */
  785.         cput(c);          /* Just output it    */
  786.         break;
  787.           }                  /* Switch ends        */
  788.         }                  /* Line for loop    */
  789. end_line:   if (c == '\n') {            /* Compiling at EOL?    */
  790.         putchar('\n');            /* Output newline, if    */
  791.         if (infile->fp == NULL)        /* Expanding a macro,    */
  792.             wrongline = TRUE;        /* Output # line later    */
  793.         }
  794.     }                    /* Continue until EOF    */
  795. }
  796.  
  797. output(c)
  798. int        c;
  799. /*
  800.  * Output one character to stdout -- output() is passed as an
  801.  * argument to scanstring()
  802.  */
  803. {
  804. #if COMMENT_INVISIBLE
  805.     if (c != TOK_SEP && c != COM_SEP)
  806. #else
  807.     if (c != TOK_SEP)
  808. #endif
  809.         putchar(c);
  810. }
  811.  
  812. FILE_LOCAL
  813. sharp()
  814. /*
  815.  * Output a line number line.
  816.  */
  817. {
  818.     register char        *name;
  819.  
  820.     if (keepcomments)            /* Make sure # comes on    */
  821.         putchar('\n');            /* a fresh, new line.    */
  822.     printf("#%s %d", LINE_PREFIX, line);
  823.     if (infile->fp != NULL) {
  824.         name = (infile->progname != NULL)
  825.         ? infile->progname : infile->filename;
  826.         printf(" \"%s\"", name); 
  827.     }
  828.     putchar('\n');
  829.     wrongline = FALSE;
  830. }
  831.